package gemini.castor.ui.client.page.navigation.loginwidget;

import gemini.basic.model.MonthlyPoint;
import gemini.basic.model.User;
import gemini.castor.ui.client.constants.I18nConstants;
import gemini.castor.ui.client.utils.GuiUtils;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Panel;

public class LoginInfoWidget extends Composite {

	private I18nConstants constants;

	@UiTemplate("LoginInfoWidget.ui.xml")
	interface MyUiBinder extends UiBinder<Panel, LoginInfoWidget> {
	}

	private static final MyUiBinder binder = GWT.create(MyUiBinder.class);

	public LoginInfoWidget() {
		initWidget(binder.createAndBindUi(this));
		constants = GWT.create(I18nConstants.class);
	}

	@UiField
	HTML htmFullnameInfo;

	@UiField
	HTML htmStatusInfo;

	@UiField
	HTML htmDiscaleInfo;

	@UiField
	HTML htmLevelInfo;

	@UiField
	HTML htmMonthlyPoint;

	@UiField
	Button btnLogout;

	@UiHandler("btnLogout")
	void onClickLogout(ClickEvent event) {
		fireEvent(new LoginEvent(LoginEvent.ForwardType.LOGOUT));
	}

	public void loadData(User result) {
		htmFullnameInfo.setHTML(result.getPerson().getFirstName() + " "
				+ result.getPerson().getLastName());
		htmStatusInfo.setHTML(constants.htmStatus() + ": "
				+ result.getUserStatus().getName());
		htmDiscaleInfo.setHTML(constants.htmDiscale()
				+ ": "
				+ String.valueOf(result.getPerson().getDistributor()
						.getDiscountScale()) + " %");
		htmLevelInfo.setHTML(constants.htmLevel() + ": "
				+ result.getPerson().getDistributor().getLevel().getName());

		int personalPoint = 0;
		int groupPoint = 0;
		MonthlyPoint currentMP = GuiUtils.getCurrentMonthlyPoint(result.getPerson().getDistributor().getMonthlyPoints());
		if(currentMP != null){
			personalPoint = currentMP.getPersonalPoint();
			groupPoint = currentMP.getGroupPoint();
		}

		htmMonthlyPoint.setHTML(constants.htmCurrentPoint() + ": "
				+ (personalPoint + groupPoint) + "(" + personalPoint + ")");
	}
	
	public HandlerRegistration addLoginFormHandler(LoginHandler handler) {
		return this.addHandler(handler, LoginEvent.getType());
	}
}
